package com.tool.main;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlReader
{
	
	public static Map getParams(InputStream is)
		throws Exception
	{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(is);
		Map result = new HashMap();
		Element root = doc.getRootElement();
		String beanName = root.attributeValue("name");
		result.put("Bean", beanName);
		result.put("bean",
				beanName.substring(0, 1).toLowerCase() + beanName.substring(1));
		result.put("package", root.attributeValue("package"));
		result.put("TABLE", "`" + root.attributeValue("table") + "`");
		if ((root.attribute("auto_increment") == null)
				|| (!"false".equalsIgnoreCase(root.attribute("auto_increment")
						.getValue())))
			result.put("auto_increment", "true");
		else
		{
			result.put("auto_increment", "false");
		}
		
		List fields = new ArrayList();
		List columns = new ArrayList();
		StringBuffer cols = new StringBuffer();
		StringBuffer _cols = new StringBuffer();
		StringBuffer item_cols = new StringBuffer();
		StringBuffer update_sql = new StringBuffer();
		List list = root.selectNodes("property");
		for (int i = 0; i < list.size(); i++)
		{
			Element elem = (Element) list.get(i);
			Map field = new HashMap();
			String name = elem.attributeValue("name");
			String col = elem.attribute("col") == null ? name.toUpperCase()
					: elem.attributeValue("col");
			String javaType = elem.attribute("javaType") == null ? "String"
					: elem.attributeValue("javaType");
			
			field.put("name", name);
			field.put("Name",
					name.substring(0, 1).toUpperCase() + name.substring(1));
			field.put("col", col);
			field.put("javaType", javaType);
			fields.add(field);

			
			Map column = new HashMap();
			column.put("columnName", col);
			column.put("typeName", name);
			column.put("propertyName", name);
			
			columns.add(column);
			if (i < list.size() - 1)
			{
				cols.append("`").append(col).append("`,");
				_cols.append("#{").append(name).append("},");
				item_cols.append("#{item.").append(name).append("},");
				update_sql.append("`").append(col).append("`=").append("#{")
						.append(name).append("},");
			}
			else
			{
				cols.append("`").append(col).append("`");
				_cols.append("#{").append(name).append("}");
				item_cols.append("#{item.").append(name).append("}");
				update_sql.append("`").append(col).append("`=").append("#{")
						.append(name).append("}");
			}
		}
		result.put("fields", fields);
		result.put("COLS", cols.toString());
		result.put("_COLS", _cols.toString());
		result.put("ITEM_COLS", item_cols.toString());
		result.put("UPDATE_SQL", update_sql.toString());
		
		result.put("columns", columns);
		System.out.println("Load Config Success");
		return result;
	}
}
